﻿using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Web;

namespace Xwltz.Framework.Helper
{
    /// <summary>
    /// 请求帮助类
    /// </summary>
    public class RequestHelper
    {
        public static string GetScriptNameQueryString => HttpContext.Current.Request.ServerVariables["QUERY_STRING"];

        public static string GetScriptName => HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"];

        public static string GetScriptUrl => GetScriptNameQueryString == "" ? GetScriptName : $"{GetScriptName}?{GetScriptNameQueryString}";

        public static string GetScriptNameQuery => HttpContext.Current.Request.Url.Query;

        [DllImport("wininet")]
        private static extern bool InternetGetConnectedState(out int connectionDescription, int reservedValue);

        public static bool IsConnectedInternet()
        {
            return InternetGetConnectedState(out _, 0);
        }

        public static string UrlEncode(string str)
        {
            string result;
            if (string.IsNullOrEmpty(str))
            {
                result = "";
            }
            else
            {
                str = str.Replace("'", "");
                result = HttpContext.Current.Server.UrlEncode(str);
            }
            return result;
        }

        public static string UrlDecode(string str)
        {
            var result = string.IsNullOrEmpty(str) ? "" : HttpContext.Current.Server.UrlDecode(str);
            return result;
        }

        public static string GetIp()
        {
            var result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            var result2 = string.IsNullOrEmpty(result) ? "127.0.0.1" : result;
            return result2;
        }

        public static string BuildUrl(string url, string param)
        {
            string result;
            if (url.IndexOf(param, StringComparison.Ordinal) > 0)
            {
                string url2;
                if (url.IndexOf("&", url.IndexOf(param, StringComparison.Ordinal) + param.Length, StringComparison.Ordinal) > 0)
                {
                    url2 = url.Substring(0, url.IndexOf(param, StringComparison.Ordinal) - 1) + url.Substring(url.IndexOf("&", url.IndexOf(param, StringComparison.Ordinal) + param.Length, StringComparison.Ordinal) + 1);
                }
                else
                {
                    url2 = url.Substring(0, url.IndexOf(param, StringComparison.Ordinal) - 1);
                }
                result = url2;
            }
            else
            {
                result = url;
            }
            return result;
        }

        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }

        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }


        public static string GetServerString(string strName)
        {
            var result = HttpContext.Current.Request.ServerVariables[strName] == null ? "" : HttpContext.Current.Request.ServerVariables[strName];
            return result;
        }

        /// <summary>
        /// 获取该请求的跳转地址
        /// </summary>
        /// <returns></returns>
        public static string GetUrlReferrer()
        {
            string retVal = null;
            try
            {
                if (HttpContext.Current.Request.UrlReferrer != null)
                    retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch
            {
                // ignored
            }

            var result = retVal ?? "";
            return result;
        }

        /// <summary>
        /// 获取该请求完整的HOST信息
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            var request = HttpContext.Current.Request;
            var result = !request.Url.IsDefaultPort ? $"{request.Url.Host}:{request.Url.Port}" : request.Url.Host;
            return result;
        }

        /// <summary>
        /// 获取该请求的HOST信息
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }

        /// <summary>
        /// 获取该请求的DNS信息
        /// </summary>
        /// <returns></returns>
        public static string GetDnsSafeHost()
        {
            return HttpContext.Current.Request.Url.DnsSafeHost;
        }

        /// <summary>
        /// 获取该请求的QueryString
        /// </summary>
        /// <returns></returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        /// <summary>
        /// 获取该请求是否为浏览器请求
        /// </summary>
        /// <returns></returns>
        public static bool IsBrowser()
        {
            string[] browserName = {
                "ie",
                "opera",
                "netscape",
                "mozilla",
                "konqueror",
                "firefox"
            };
            var curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            return browserName.Any(t => curBrowser.IndexOf(t, StringComparison.Ordinal) >= 0);
        }

        /// <summary>
        /// 获取该请求是否为搜索引擎
        /// </summary>
        /// <returns></returns>
        public static bool IsSearchEngines()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                return false;
            }

            var searchEngine = new[]
            {
                "google",
                "yahoo",
                "msn",
                "baidu",
                "sogou",
                "sohu",
                "sina",
                "163",
                "lycos",
                "tom",
                "yisou",
                "iask",
                "soso",
                "gougou",
                "zhongsou"
            };
            var tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            return searchEngine.Any(t => tmpReferrer.IndexOf(t, StringComparison.Ordinal) >= 0);
        }

        /// <summary>
        /// 获取请求的URL
        /// </summary>
        /// <returns></returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }

        /// <summary>
        /// 获取请求的页面名称
        /// </summary>
        /// <returns></returns>
        public static string GetPageName()
        {
            var urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }

        /// <summary>
        /// 获取参数的数量
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }
    }
}
